import 'dart:developer';
import 'dart:io';
import 'package:path/path.dart';
import 'dart:typed_data';
import 'package:flutter/services.dart';
import 'package:sqflite/sqflite.dart';

class DbManger{
  //数据库版本
  static const int _VERSION=1;
  //数据库名称
  static const String DB_NAME='diugou_core.db';
  //数据库实例
  static Database _datebase;

  static init() async {
    var databasePath = await getDatabasesPath();
    String dbNAme=DB_NAME;
    String path=databasePath+dbNAme;
    if(Platform.isIOS){
      path=databasePath+"/"+dbNAme;
    }
    var exists = await databaseExists(path);
    if (!exists) {
      //确保父目录存在
      try {
        await Directory(dirname(path)).create(recursive: true);
      } catch (_) {}
      // 从assets复制
      ByteData data = await rootBundle.load(join("assets", "diugou_core.db"));
      List<int> bytes =
      data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
      // 写入并刷新写入的字节
      await File(path).writeAsBytes(bytes, flush: true);
    }

    //打开数据库
    _datebase = await openDatabase(path, version: 1,
        onCreate: (Database db, int version) async {
          //如果需要建表,这里可以建表
          //await db.execute('');
        });
  }

  /**
   * 判断数据表是否存在
   */
  static isTbleExits(String tableName) async {
    await getCurrentDatabase();
    String sql="select * from Sqlite_master where type='table' and name='$tableName'";
    var res=await _datebase.rawQuery(sql);
    return res!=null && res.length>0;
  }

  /**
   * 获取数据库实例
   */
  static Future<Database>getCurrentDatabase() async{
    if(_datebase==null){
      await init();
    }
    return _datebase;
  }

  static close(){
    _datebase.close();
    _datebase=null;
  }
}